package cn.agiledata.bank.interest.dao.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.Restrictions;
import org.springframework.context.ApplicationContext;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateTemplate;

import cn.agiledata.bank.hibernateBean.BankrollType;
import cn.agiledata.bank.hibernateBean.InterestRate;
import cn.agiledata.bank.interest.dao.IInterestRateDAO;
import com.vnv.infrastructure.exception.IPBException;
import com.vnv.infrastructure.logic.IPBHibernate3BaseMgr;

/**
 * Data access object (DAO) for domain model class InterestRate.
 * @see cn.agiledata.bank.hibernatebean.InterestRate
 * @author MyEclipse - Hibernate Tools
 */
public class InterestRateDAOImpl extends IPBHibernate3BaseMgr implements IInterestRateDAO{

    private static final Log log = LogFactory.getLog(InterestRateDAOImpl.class);
    /**
	 *@see cn.agiledata.bank.interest.dao.IInterestRateDAO#getListByRateNum(int)
	 */
	public List getListByRateNum(Long rateId) {
		List list=null;
		try {
			HibernateTemplate ht = this.getHibernateTemplate();
//			DetachedCriteria detachedCriteria = DetachedCriteria.forClass(InterestRate.class); 
//			detachedCriteria.add(Restrictions.eq(("bankrollType.rateId"), (rateId))).addOrder(Order.desc("useBegin")); 
//
//			list = ht.findByCriteria(detachedCriteria);
			return ht.find("from InterestRate rate where rate.bankrollType.rateId=? order by rate.useBegin desc",new Object[]{rateId});
		} catch (DataAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}
	 
	public List getListByRateNum(Long rateId, Date beginDate, Date endDate) {
		List list=null;
		try {
			HibernateTemplate ht = this.getHibernateTemplate();
//			DetachedCriteria detachedCriteria = DetachedCriteria.forClass(InterestRate.class); 
//			detachedCriteria.add(Restrictions.eq(("rateId"), (rateId))).add(Restrictions.between("useBegin",beginDate,endDate)).addOrder(Order.desc("useBegin")); 
//
//			list = ht.findByCriteria(detachedCriteria);
			return ht.find("from InterestRate rate where rate.bankrollType.rateId=? and rate.useBegin>? and rate.useBegin<? order by rate.useBegin desc",new Object[]{rateId,beginDate,endDate});
		} catch (DataAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}

	/**
	 *@see cn.agiledata.bank.interest.dao.IInterestRateDAO#save(cn.agiledata.bank.hibernateBean.InterestRate)
	 */
	public void save(InterestRate node) {
		try {
			HibernateTemplate ht = this.getHibernateTemplate();
			ht.saveOrUpdate(node);
		} catch (DataAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * 实现，从数据库获取某利率号对应的利率值
	 * @param rateNum 利率号
	 * */
	public InterestRate getLastRate(Long rateId) throws IPBException{
		List list = null;
		try {
			HibernateTemplate ht = this.getHibernateTemplate();
			DetachedCriteria detachedCriteria = DetachedCriteria.forClass(BankrollType.class);
			detachedCriteria.add(Restrictions.eq(("rateId"), (rateId)));
			
			list = ht.findByCriteria(detachedCriteria,0,1);
			if(list.size()>0){//业务上rateId唯一理论上size===1
				InterestRate rate = ((BankrollType)list.get(0)).getRateCurr();
				if(rate!=null)
					return rate;
			}
			throw new IPBException("10001","某利率号对应利率值不存在","利率号="+rateId);
//			list = ht.find("from InterestRate rate where rate.bankrollType.rateId=? and rate.useBegin>? and rate.useBegin<? order by rate.useBegin desc",new Object[]{rateId,beginDate,endDate});
//			int size = list.size(); 
//			if(size>0){
//				Date date = (Date)list.get(0);
//				detachedCriteria=DetachedCriteria.forClass(InterestRate.class);
//				detachedCriteria.add(Restrictions.eq(("rateId"), (rateId))).add(Restrictions.eq("useBegin",date));
//				
//				list = ht.findByCriteria(detachedCriteria,0,1);
//				if(size>0){
//					return (InterestRate)list.get(0);
//				}else{
//					throw new IPBException(10001,"某利率号对应利率值不存在","利率号="+rateId);
//				}
//			}else{
//				throw new IPBException(10001,"某利率号对应利率值不存在","利率号="+rateId);
//			}
			
		} catch (DataAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IPBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	protected void initDao() {
		//do nothing
	}
    
//    public void save(InterestRate transientInstance) {
//        log.debug("saving InterestRate instance");
//        try {
//            getHibernateTemplate().saveOrUpdate(transientInstance);
//            log.debug("save successful");
//        } catch (RuntimeException re) {
//            log.error("save failed", re);
//            throw re;
//        }
//    }
    
	public void delete(InterestRate persistentInstance) {
        log.debug("deleting InterestRate instance");
        try {
            getHibernateTemplate().delete(persistentInstance);
            log.debug("delete successful");
        } catch (RuntimeException re) {
            log.error("delete failed", re);
            throw re;
        }
    }
    
    public InterestRate findById( java.lang.Long id) {
        log.debug("getting InterestRate instance with id: " + id);
        try {
            InterestRate instance = (InterestRate) getHibernateTemplate()
                    .get("cn.agiledata.bank.hibernatebean.InterestRate", id);
            return instance;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }
    
    
    public List findByExample(InterestRate instance) {
        log.debug("finding InterestRate instance by example");
        try {
            List results = getSession()
                    .createCriteria("cn.agiledata.bank.hibernatebean.InterestRate")
                    .add(Example.create(instance))
            .list();
            log.debug("find by example successful, result size: " + results.size());
            return results;
        } catch (RuntimeException re) {
            log.error("find by example failed", re);
            throw re;
        }
    }    
    
    public InterestRate merge(InterestRate detachedInstance) {
        log.debug("merging InterestRate instance");
        try {
            InterestRate result = (InterestRate) getHibernateTemplate()
                    .merge(detachedInstance);
            log.debug("merge successful");
            return result;
        } catch (RuntimeException re) {
            log.error("merge failed", re);
            throw re;
        }
    }

    public void attachDirty(InterestRate instance) {
        log.debug("attaching dirty InterestRate instance");
        try {
            getHibernateTemplate().saveOrUpdate(instance);
            log.debug("attach successful");
        } catch (RuntimeException re) {
            log.error("attach failed", re);
            throw re;
        }
    }
    
    public void attachClean(InterestRate instance) {
        log.debug("attaching clean InterestRate instance");
        try {
            getHibernateTemplate().lock(instance, LockMode.NONE);
            log.debug("attach successful");
        } catch (RuntimeException re) {
            log.error("attach failed", re);
            throw re;
        }
    }

	public static InterestRateDAOImpl getFromApplicationContext(ApplicationContext ctx) {
    	return (InterestRateDAOImpl) ctx.getBean("InterestRateDAO");
	}
}